/* components */
import TaskAllotSelect from '@src/modules/task/edit/components/TaskAllotSelect/TaskAllotSelect.vue'
import BaseAlert from '@src/component/common/BaseAlert/index.ts'

/* utils */
import _ from 'lodash'
import { dateDiff } from 'pub-bbx-utils';  
import i18n from '@src/locales'
import { getRootWindow } from '@src/util/dom';
import { isEmpty } from '@src/util/type'
/* constant */
import { 
  TASK_NO_EXECUTOR_MESSAGE,
  PLATN_TASK_PERIOD_NOT_ZERO_MESSAGE,
  PLATN_TASK_CREATE_TIME_NOT_GREATER_THEAN_PERIOD_TIME_MESSAGE,
  PLATN_TASK_END_TIME_NOT_GREATER_ONE_YEAR_MESSAGE,
  PLATN_TASK_PERFORM_NUMBER_MAX_MESSAGE
} from '@src/model/const/Alert.ts'
import { PLAN_TASK_MAX_DAY, PLAN_TASK_MAX_PERFORM_NUMBER } from '@src/model/const/Number.ts';
import { isCalendar } from '@src/util/CalendarUtil';
const NumberReg = /\D/g;

const PlanTaskEditForm = {
  name: 'plan-task-edit-form',
  initject: ['initData'],
  props: {
    isShowPlanStartTime: {
      type: Boolean,
      default: false
    },
    isShowPlanEndTime: {
      type: Boolean,
      default: false
    },
    originForm: {
      type: Object,
      default: () => ({})
    },
    qualityField: {
      type: Object,
      default: () => ({})
    },
    taskConfig: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      abortList: [
        {
          label: i18n.t('task.edit.byDueDate'),
          value: 'date'
        },
        {
          label: i18n.t('task.edit.byExecutedNum'),
          value: 'times'
        }
      ],
      form: this.initForm(),
      rules: {
        name: [
          { required: true, message: i18n.t('common.base.isRequire'), trigger: 'blur' },
        ],
        createRule: [
          { required: true,  message: i18n.t('common.base.isRequire'), trigger: 'change'}
        ],
        planTimeType: [
          { required: true,  message: i18n.t('common.base.isRequire'), trigger: 'change'}
        ],
        advance: [
          { required: true,  message: i18n.t('common.base.isRequire'), trigger: 'blur'}
        ],
        period: [
          { required: true,  message: i18n.t('common.base.isRequire'), trigger: 'blur'}
        ],
        endTime: [
          { required: true,  message: i18n.t('common.base.isRequire'), trigger: 'change'}
        ],
        endNum: [
          { required: true,  message: i18n.t('common.base.isRequire'), trigger: 'blur'}
        ]
      },
      formValidation: {
        name: true,
        period: true,
        periodUnit: true,
        endTime: true,
        endNum: true,
        advance: true,
        planTimeType:true
      },
      isEdit: false,
      pending: false,
      // 重复周期列表
      repetitionPeriodList: [
        {
          label: i18n.t('common.time.day'),
          value: i18n.t('common.time.day')
        },
        {
          label: i18n.t('common.time.week'),
          value: i18n.t('common.time.week')
        },
        {
          label: i18n.t('common.time.month'),
          value: i18n.t('common.time.month')
        }
      ],
      show: false,
      title: i18n.t('task.edit.planSetting'),
      isCalendar,
      createSingleRuleDisabled: false,
    }
  },
  computed: {
    /* 是否是 按截止日期 */
    isEndTime() {
      return this.form?.endSetting?.select == this.abortList?.[0]?.value;
    },
    taskAllotSelectEl() {
      return this.$refs.TaskAllotSelect;
    },
    validation() {
      let { name, period, periodUnit, endTime, endNum, advance, planTimeType } = this.formValidation;
      return {
        name: name ? '' : i18n.t('common.base.isRequire'),
        period: period ? '' : i18n.t('common.base.isRequire'),
        periodUnit: periodUnit ? '' : i18n.t('common.base.required'),
        endTime: endTime ? '' : i18n.t('common.base.required'),
        endNum: endNum ? '' : i18n.t('common.base.isRequire'),
        advance: advance ? '' : i18n.t('common.base.isRequire'),
        planTimeType: planTimeType ? '' : i18n.t('common.base.isRequire')
      }
    },
    options() {
      let options = []
      if(this.isShowPlanStartTime) options.push({value: '1', label: i18n.t('common.form.type.planStartTime')})
      if(this.isShowPlanEndTime) options.push({value: '2', label: i18n.t('common.form.type.planEndTime')})
      return options
    },
    // 华大基因灰度
    isBgiSaas() {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow.grayAuth?.bgiSaas)
    }
  },
  methods: {
    /* 更改派单类型 */
    changeAllotType(value) {
      this.form.allotSetting.allotType = value;
    },
    /* 更改协同人 */
    changeSynergies(value) {
      this.form.allotSetting.synergies = value;
    },
    /* 更改协同人 */
    changeExecutors(value) {
      this.form.allotSetting.executors = value;
    },
    /* 更改重复周期 */
    changePeriod(value) {
      // this.form.periodSetting.period = this.formatNumber(value);
      this.form.period = this.formatNumber(value);

      // this.validate();
    },
    /* 更改重复周期 */
    changeEndSettingNum(value) {
      // this.form.endSetting.num = this.formatNumber(value);
      this.form.endNum = this.formatNumber(value);

      // this.validate();
    },
    /* 更改计划时间类型 */
    changePlanTimeType(value) {
      this.form.planTimeType = this.formatNumber(value);
      // this.validate();
    },
    /* 更改截止日期前天数 */
    changeAdvance(value) {
      this.form.advance = this.formatNumber(value);
      // this.validate();
    },
    fetchExeinsyn(customerId = '') {
      const TaskAllotSelectEl = this.taskAllotSelectEl;
      TaskAllotSelectEl && TaskAllotSelectEl.fetchExeinsynWithCustomerManager(customerId);
    },
    formatNumber(value) {
      return value.replace(NumberReg, '');
    },
    getValidatorValue(key) {
      let { periodSetting, endSetting, period, periodUnit } = this.form;

      if(key == 'period') return period
      else if(key == 'periodUnit') return periodUnit
      else if(key == 'endTime') return endSetting.select == 'date' ? endSetting.time : true
      else if(key == 'endNum') return endSetting.num
      
      return this.form[key];
    },
    initForm() {
      const initForm = {
        // 计划任务id
        id: '',
        // 计划任务名称
        name: '',
        // 周期设置
        periodSetting: {
          // 周期数
          // period: 1,
          // 周期单位(天、周、月)
          // periodUnit: '天'
        },
        // 周期数
        period: 1,
        // 周期单位(天、周、月)
        periodUnit: '天',
        // 截止设置
        endSetting: {
          // 截止单位(times、date)
          select: 'date',
          // num: 1,
          // time: ''
        },
        endNum: 1,
        endTime: '',
        //计划时间类型
        planTimeType: '',
        // 提前几天创建
        advance: 1,
        // 生成规则
        createRule: 0,
        // 派单设置
        allotSetting: {
          // 派单方式 (normal、pool、auto)
          allotType: 'normal',
          // 协同人
          synergies: [],
          // 负责人
          executors: []
        }
      }
      // 初始化派单设置
      this.taskAllotSelectEl?.changeAllotData(initForm.allotSetting);
      return initForm;
    },
    /** 
     * @description 提交
    */
    onSubmit: _.debounce(function(){

      this.$refs.form.validate((valid) => {
        if (valid) {
          // 效验是否必填
          // let validated = this.validate();
          // if (!validated) {
          //   return console.warn('Caused: onSubmit validated is false')
          // }
          let validated = this.validateDataCorrectly();
          if (!validated) {
            return console.warn('Caused: onSubmit validated validateDataCorrectly return value is false')
          }

          // 判断是否选择工单负责人
          let params = this.unPackDataToParams();
          let { allotSetting = {} } = params;
          if(!allotSetting.executorId && allotSetting.allotType == 'normal' ) {
            return this.$platform.alert(TASK_NO_EXECUTOR_MESSAGE);
          }
          
          this.$emit('submit', params);

        } else {
          console.warn('Caused: onSubmit validated is false')
          return false;
        }
      });
    }, 500),
    /** 
     * @description 解析数据
     * @param {Object} data 数据
    */
    packData(data = {}) {
      const { advance = '',planTimeType = '', allotSetting = {}, endSetting = {}, id = '', name = '', periodSetting = {}, createRule = 0 } = data;
      const { allotType = 'normal', synergies = [], executorId = '', executorName = '' } = allotSetting;
      const { value = '', endBy = '' } = endSetting;
      const { period = 1, periodUnit = '天' } = periodSetting;
      const IsEndTime = endBy == 'date';

      let form = {
        // 计划任务id
        id,
        // 计划任务名称
        name,
        // 周期设置
        periodSetting: {
          // 周期数
          // period,
          // 周期单位(天、周、月)
          // periodUnit
        },
        // 周期数
        period,
        // 周期单位(天、周、月)
        periodUnit,
        // 截止设置
        endSetting: {
          // 截止单位(times、date)
          select: endBy,
          // num: IsEndTime ? 1 : value,
          // time: IsEndTime ? value : ''
        },
        endNum: IsEndTime ? 1 : value,
        endTime: IsEndTime ? value : '',
        // 计划时间类型
        planTimeType: String(planTimeType),
        // 提前几天创建
        advance: advance === 0 ? '0' : advance,
        // 生成规则
        createRule,
        // 派单设置
        allotSetting: {
          // 派单方式 (normal、pool、auto)
          allotType,
          // 协同人
          synergies,
          // 负责人
          executors: [{ userId: executorId, displayName: executorName }]
        }
      }

      const TaskAllotSelectEl = this.taskAllotSelectEl;
      TaskAllotSelectEl && TaskAllotSelectEl.changeAllotData(form.allotSetting);

      // 开启华大基因灰度，并且包含质保时，默认选中每次按产品生成多个工单，并且每次生成一个工单禁止选择
      if (!isEmpty(this.qualityField) && this.isBgiSaas) {
        form.createRule = 1
        this.createSingleRuleDisabled = true
      }

      this.$set(this, 'form', form);
    },
    reset() {
      this.form = this.initForm();
    },
    /** 
     * @description 切换状态
     * @param {Object} params 参数
     * @param {Boolean} params.show 是否显示
     * @param {Object} params.data 需要解析的数据
    */
    toggle(show = true, data = {}) {
      if (data && Object.keys(data).length > 0) {
        this.isEdit = true;
        this.packData(data);
      } else {
        this.isEdit = false;
      }

      this.show = show;
      // this.validate();
    },
    togglePending(pending = false) {
      this.pending = pending;
    },
    unPackDataToParams(data = {}) {
      let { id, name, periodSetting = {}, endSetting = {}, advance, planTimeType, allotSetting, createRule, period, periodUnit, endNum, endTime } = this.form;
      let { select, time, num } = endSetting;
      let { allotType, synergies, executors } = allotSetting;
      let executor = executors?.[0] || {};
      let params = {
        id,
        name,
        periodSetting: {
          period,
          periodUnit
        },
        endSetting: {
          endBy: select,
          value: this.isEndTime ? endTime : endNum
        },
        planTimeType,
        advance,
        allotSetting: {
          allotType,
          synergies,
          executorId: executor.userId,
          executorName: executor.displayName
        }
      };
      // 生成规则受华大基因灰度控制
      if(this.isBgiSaas) {
        params.createRule = createRule
      }

      return params;
    },
    validate() {
      const keys = Object.keys(this.formValidation);
      let val = null;

      return (
        keys
          .map(key => {
            val = this.getValidatorValue(key);
            this.formValidation[key] = !!val
            if(key=='planTimeType'&&!this.isCalendar){
              this.formValidation[key] = true;
            }
            return this.formValidation[key]
          })
          .every(bool => bool)
      )
    },
    /** 
     * @description 效验数据正确性
     */
    validateDataCorrectly() {
      let { advance = '', endSetting = {}, periodSetting = {}, period, periodUnit = '天', endNum, endTime = ''} = this.form;
      let { num, time = '', select = '' } = endSetting;
      // let { period, periodUnit ='天' } = periodSetting;
      let IsEndTime = select == 'date';
      let validated = true;
      
      try {
        period = isNaN(Number(period)) ? 0 : Number(period);
        advance = isNaN(Number(advance)) ? 0 : Number(advance);
  
        if (period == 0){
          this.$platform.alert(PLATN_TASK_PERIOD_NOT_ZERO_MESSAGE)
          return validated = false;
        }
        
        // TODO 国际化待办
        if(periodUnit == '天') {
          if(advance > period) {
            this.$platform.alert(PLATN_TASK_CREATE_TIME_NOT_GREATER_THEAN_PERIOD_TIME_MESSAGE)
            return validated = false;
          }
        }
        else if(periodUnit == '周') {
          if(advance > period * 7) {
            this.$platform.alert(PLATN_TASK_CREATE_TIME_NOT_GREATER_THEAN_PERIOD_TIME_MESSAGE)
            return validated = false;
          }
        }
        else if(periodUnit == '月') {
          if(advance > period * 30) {
            this.$platform.alert(PLATN_TASK_CREATE_TIME_NOT_GREATER_THEAN_PERIOD_TIME_MESSAGE)
            return validated = false;
          }
        }
  
        if(IsEndTime) {
          let _dateDiff = null
          if(this.isCalendar) {
            let planTimeStartOrEnd = this.form.planTimeType
            if(planTimeStartOrEnd == '1') {
              _dateDiff = dateDiff(this.originForm.planStartTime, endTime);
            }else if(planTimeStartOrEnd == '2'){
              _dateDiff = dateDiff(this.originForm.planEndTime, endTime);
            }else {
              return validated = false;
            }
          }else {
            _dateDiff = dateDiff(this.originForm.planTime, endTime);
          }
          if(_dateDiff > PLAN_TASK_MAX_DAY) {
            this.$platform.alert(PLATN_TASK_END_TIME_NOT_GREATER_ONE_YEAR_MESSAGE)
            return validated = false;
          }
        } else {
          if(Number(endNum) > PLAN_TASK_MAX_PERFORM_NUMBER){
            this.$platform.alert(PLATN_TASK_PERFORM_NUMBER_MAX_MESSAGE)
            return validated = false;
          }
        }
      } catch (error) {
        validated = false;
        console.warn('validateDataCorrectly -> error', error)
      }

      return validated;
    }
  },
  components: {
    [TaskAllotSelect.name]: TaskAllotSelect,
    BaseAlert
  }
}

export default PlanTaskEditForm;